#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
int main()
{
    pid_t id = fork();
    if(id < 0)
    {
        perror("fork");
        return 0;
    }
    if(id == 0)
    {
        int cn = 5;
        while(cn--)
        {
            printf("i am child process,pid: %d, ppid: %d\n", getpid(), getppid());
            sleep(1);
        }
        exit(1);
    }
    else if(id > 0)
    {       
        //int cn = 10;
        //while(cn--)
        printf("i am parent processpid: %d, ppid: %d\n", getpid(), getppid());
        sleep(1);
        
        int status;
        //pid_t ret = waitpid(id, &status, 0);//阻塞
        while(1)//轮询
        {

            pid_t ret = waitpid(id, &status, WNOHANG);//阻塞
            if(ret > 0)
            {
                //printf("wait success, ret: %d, exit sig: %d, exit code: %d\n", ret, status&0x7f, (status>>8)&0xff);
                if(WIFEXITED(status))
                {
                    printf("进程是正常跑完的,退出码:%d\n",WEXITSTATUS(status)); 
                }
                else{
                    printf("进程出异常了:%d",status&0x7f);
                }
                break;
            }
            else if(ret < 0){
                printf("wait err\n");
                break;
            }
            else{
                printf("子进程还没有退出\n");
                sleep(1);
            }
        }
        sleep(5);
    }
    return 0;
}
